package com.mspbots.rule.exceptions.cw;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.mspbots.cw.request.TenantTimeEntryDTO;
import lombok.extern.slf4j.Slf4j;
import org.jeasy.rules.annotation.Condition;
import org.jeasy.rules.annotation.Fact;
import org.jeasy.rules.annotation.Rule;
import org.springframework.util.ObjectUtils;

import java.util.Iterator;

/**
 * com.mspbots.rule.exceptions.timeentry.NotEnoughWords
 *
 * @author Jun Zhou
 * @date 12:25 2019/7/1
 **/
@Slf4j
@Rule(name = "NotEnoughWords", description = "Long time log more than 2 hours, with less than 100 letters of time log notes")
public class NotEnoughWords extends CwBaseRule implements IcwBaseRule {


    @Condition
    @Override
    public boolean condition(@Fact(FACT) TenantTimeEntryDTO entry) {
        try {
            if (!setUserMapping(entry.getTenantUserId()) || super.checkMessage(entry)) {
                return false;
            }
            //add filter 'travel'
            if ("travel".equalsIgnoreCase(entry.getExtend().findPath("workType").get("name").asText())) {
                return false;
            }

            JsonNode params = JSONUtil.isNull(this.tenantRuleDTO.getRuleParams()) ?
                    this.tenantRuleDTO.getSysParams() : this.tenantRuleDTO.getRuleParams();
            if (ObjectUtils.isEmpty(params)) {
                log.error("NotEnoughWords rule params is null...");
                return false;
            }
            Iterator<String> iterator = params.fieldNames();
            String fieldName = iterator.hasNext() ? iterator.next() : "";
            return entry.getActualHours() > 2 && entry.getDescription().length() < params.get(fieldName).asInt(0);
        } catch (Exception e) {
            log.error("NotEnoughWords rule execute error [{}] : {}", e.getStackTrace()[0].getLineNumber(), e.getMessage());
        }
        return false;
    }


}
